<template>
  <div id="app">
    <div>
      <span>姓名:</span>
      <input v-model.trim="person.name" type="text" />
    </div>
    <div>
      <span>年龄:</span>
      <input v-model.number="person.age" type="number" />
    </div>
    <div>
      <span>性别:</span>
      <select v-model="person.sex">
        <option value="男">男</option>
        <option value="女">女</option>
      </select>
    </div>
    <div>
      <button @click="add">添加</button>
      <button @click="amend">修改</button>
    </div>
    <div>
      <table
        border="1"
        cellpadding="10"
        cellspacing="0"
      >
        <tr>
          <th>序号</th>
          <th>姓名</th>
          <th>年龄</th>
          <th>性别</th>
          <th>操作</th>
        </tr>
        <tr v-for="(item,index) in arr" :key="item.id">
          <td>{{index + 1}}</td>
          <td>{{item.name}}</td>
          <td>{{item.age}}</td>
          <td>{{item.sex}}</td>
          <td>
            <button @click="del(item.id)">删除</button>
            <button @click="edit(item.id)">编辑</button>
          </td>
        </tr>
      </table>
    </div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      arr:[
        {
          id:11,
          name:'Tom',
          age:19,
          sex:'男'
        },
        {
          id:22,
          name:'Jone',
          age:21,
          sex:'女'
        },
      ],
      person:{
        name:'',
        age:'',
        sex:'',
        id:''
      }
    }
  },
  methods:{
    add() {
      const {name,age,sex} = this.person
      if(this.name === '' || this.age === '' || this.sex === '') return alert('请输入数据')
      this.arr.push({
        name,
        age,
        sex,
        id:Date.now()
      })
      this.person = {}
    },
    edit(id) {
      const obj = this.arr.find(item => item.id === id)
      this.person = {...obj}
    },
    amend() {
      const index = this.arr.findIndex(item => item.id === this.person.id)
      this.arr.splice(index,1,this.person)
      this.person = {}
    },
    del(id) {
      const i = this.arr.findIndex(item => item.id === id)
      this.arr.splice(i,1)
    }
  }
}
</script>
